import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from "@nestjs/common";
import { FastifyReply, FastifyRequest } from "fastify";
import { Observable, of } from "rxjs";
import { WebResult } from "src/common/web.result";

@Injectable()
export class IPInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
    const http = context.switchToHttp();
    const request: FastifyRequest = http.getRequest();
    const response: FastifyReply = http.getResponse();
    const userIP =
      request.headers["x-real-ip"] ||
      request.headers["x-forwarded-for"] ||
      request.ip ||
      request.socket.remoteAddress ||
      undefined;
    if (!userIP) {
      response.status(404);
      of(WebResult.failure(undefined, "404"));
    }

    return next.handle();
  }
}
